package com.zl.csMall.mine.order.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zl.csMall.code.LoginCacheMap;
import com.zl.csMall.code.config.token.TokenTriggerAspect;
import com.zl.csMall.mine.notice.service.NoticeService;
import com.zl.csMall.mine.order.po.Orders;
import com.zl.csMall.mine.order.service.OrderService;
import com.zl.csMall.mine.user.po.User;
import com.zl.csMall.util.Util;
import com.zl.csMall.vo.ReturnModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @description: OrderController
 * @author: ChenNing
 * @date 2025-10-22 10:09
 */
@CrossOrigin(origins = "*")
@Api(tags = "订单")
@RestController
@RequestMapping("csMall/mine/order")
public class OrderController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private NoticeService noticeService;

    private final LoginCacheMap loginCacheMap;

    public OrderController(LoginCacheMap loginCacheMap) {
        this.loginCacheMap = loginCacheMap;
    }


    /**
     * @description: 查询全部订单
     * @param content 模糊查询（仅商品编号或名称）
     * @param status 订单状态（1：待付款、2：待发货、3：待收货、4：已收货）
     * @author ChenNing
     * @date: 2025-10-22 16:54
     */
    @ApiOperation(value = "查询全部订单 - 商家", response = Orders.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "content", value = "搜索内容（仅商品编号或名称）"),
            @ApiImplicitParam(name = "status", value = "订单状态（1：待付款、2：待发货、3：待收货、4：已收货）"),
    })
    @TokenTriggerAspect
    @CrossOrigin("*")
    @GetMapping
    public ReturnModel getAll(@RequestHeader(required = false) String token,
                              @RequestParam(required = false) String content,
                              @RequestParam(required = false) Integer status,
                              @RequestParam("pageNum") int pageNum, @RequestParam("pageSize") int pageSize){
        LambdaQueryWrapper<Orders> orderQuery = new LambdaQueryWrapper<>();
        if (status != null && (status == 1 || status == 2 || status == 3 || status == 4)){
            orderQuery.eq(Orders::getStatus, status);
        }
        orderQuery.orderByDesc(Orders::getCreateDate);
        Page<Orders> orderPage = orderService.getOrderAll(orderQuery, new Page<>(pageNum, pageSize), content);
        return new ReturnModel(orderPage);
    }

    /**
     * @description: 查询用户全部订单
     * @param content 模糊查询（仅商品编号或名称）
     * @param status 订单状态（1：待付款、2：待发货、3：待收货、4：已收货）
     * @author ChenNing
     * @date: 2025-10-22 11:47
     */
    @ApiOperation(value = "查询用户订单", response = Orders.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "content", value = "搜索内容（仅商品编号或名称）"),
            @ApiImplicitParam(name = "status", value = "订单状态（1：待付款、2：待发货、3：待收货、4：已收货）"),
    })
    @TokenTriggerAspect
    @CrossOrigin("*")
    @GetMapping("user")
    public ReturnModel getOrderByUserId(@RequestHeader(required = false) String token,
                                        @RequestParam(required = false) String content,
                                        @RequestParam(required = false) Integer status,
                                        @RequestParam("pageNum") int pageNum, @RequestParam("pageSize") int pageSize){
        User user = loginCacheMap.getUser(token);

        LambdaQueryWrapper<Orders> orderQuery = new LambdaQueryWrapper<>();
        orderQuery.eq(Orders::getUserId, user.getId());
        if (status != null && (status == 1 || status == 2 || status == 3 || status == 4)){
            orderQuery.eq(Orders::getStatus, status);
        }
        Page<Orders> orderPage = orderService.getOrderAll(orderQuery, new Page<>(pageNum, pageSize), content);
        return new ReturnModel(orderPage);
    }

    @ApiOperation(value = "根据ID查询订单", response = Orders.class)
    @ApiImplicitParam(name = "id", value = "订单ID", required = true)
    @TokenTriggerAspect
    @CrossOrigin("*")
    @GetMapping("{id}")
    public ReturnModel getById(@RequestHeader(required = false) String token,
                               @PathVariable("id") Long id){
        Orders orders = orderService.getOrders(id);
        if (orders == null){
            return new ReturnModel(false, "未查询到订单信息！");
        }
        User user = loginCacheMap.getUser(token);
        Map<String, Object> userMap = new HashMap<>();
        userMap.put("username", user.getUsername());
        userMap.put("name", user.getName());
        orders.setUser(userMap);
        return new ReturnModel(orders);
    }

    /**
     * @description: 创建订单
     * @author ChenNing
     * @date: 2025-10-22 11:02
     */
    @CrossOrigin("*")
    @ApiOperation(value = "创建订单")
    @TokenTriggerAspect
    @PostMapping
    public ReturnModel addOrder(@RequestHeader(required = false) String token,
                                @Validated @RequestBody Orders orders){
        User user = loginCacheMap.getUser(token);

        long id = Util.getUuId();
        orders.setId(id);
        orders.setUserId(user.getId());
        boolean result = orderService.addOrder(orders);
        if (result){
            // 生成发货通知
            noticeService.addNotice(user.getId(), orders.getCommodityId(), orders.getRecAddressId(), id);
            return new ReturnModel();
        }
        return new ReturnModel(false, "订单创建失败！");
    }

    /**
     * @description: 订单发货
     * @param params {id: 订单ID}
     * @author ChenNing
     * @date: 2025-10-22 16:39
     */
    @CrossOrigin("*")
    @ApiOperation(value = "订单发货 - 商家")
    @ApiImplicitParam(name = "params", value = "订单ID", required = true)
    @TokenTriggerAspect
    @PutMapping("shipment")
    public ReturnModel orderShipment(@RequestHeader(required = false) String token,
                                     @RequestParam Map<String, Object> params){
        if (params == null || params.get("id") == null){
            return new ReturnModel(false, "订单ID为空！");
        }
        Orders orders = orderService.getById(Long.parseLong(params.get("id").toString()));
        if (orders == null || orders.getId() == 0){
            return new ReturnModel(false, "未查询到对应订单！");
        }
        if (orders.getStatus() == null || orders.getStatus() != 2){
            return new ReturnModel(false, "该订单不为待发货订单！");
        }
        // 待发货更为待收货
        orders.setStatus(3);
        orders.setShipmentDate(new Date());
        boolean result = orderService.updateById(orders);
        if (result){
            // 删除发货通知
            noticeService.deleteShipmentNotice(orders.getId());
            return new ReturnModel();
        }
        return new ReturnModel(false, "发货更新失败！");
    }

    /**
     * @description: 订单确认收货
     * @param params {id: 订单ID}
     * @author ChenNing
     * @date: 2025-10-22 16:49
     */
    @CrossOrigin("*")
    @ApiOperation(value = "订单确认收货")
    @ApiImplicitParam(name = "params", value = "订单ID", required = true)
    @TokenTriggerAspect
    @PutMapping("received")
    public ReturnModel orderReceived(@RequestHeader(required = false) String token,
                                     @RequestBody Map<String, Object> params){
        if (params == null || params.get("id") == null){
            return new ReturnModel(false, "订单ID为空！");
        }
        Orders orders = orderService.getById(Long.parseLong(params.get("id").toString()));
        if (orders == null || orders.getId() == 0){
            return new ReturnModel(false, "未查询到对应订单！");
        }
        if (orders.getStatus() == null || orders.getStatus() != 3){
            return new ReturnModel(false, "该订单不为待收货订单！");
        }
        // 待收货更为已收货
        orders.setStatus(4);
        orders.setReceivedDate(new Date());
        boolean result = orderService.updateById(orders);
        if (result){
            return new ReturnModel();
        }
        return new ReturnModel(false, "确认收货失败！");
    }

}
